/**
 * @author lulongwen
 * Date: 2023-09-15 21:27
 * Description:
 */

import { useCallback } from 'react';
import { useReactFlow } from 'reactflow';
import { Menu, theme } from 'antd';
import {
  CopyTwoTone,
  DeleteOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import type { Node } from 'reactflow';

function ContextMenu(props: any) {
  const { id, top, left, right, bottom, ...rest } = props;
  const { token } = theme.useToken();

  const {
    getNode,
    setNodes,
    addNodes,
    setEdges,
  } = useReactFlow();

  const items: MenuProps['items'] = [
    {
      label: '复制',
      key: 'copy',
      icon: <CopyTwoTone />,
    },
    {
      label: '删除',
      key: 'delete',
      icon: <DeleteOutlined style={{ color: token.colorError }} />,
    },
  ];

  // 复制节点
  const duplicateNode = useCallback(() => {
    const node: Node | undefined = getNode(id);
    if (!node) return;

    // console.log(24, node)
    const position = {
      x: node.position.x + 50,
      y: node.position.y + 50,
    };

    addNodes({ ...node, id: `${node.id}-copy`, position });
  }, [id, getNode, addNodes]);

  // 删除节点
  const deleteNode = useCallback(() => {
    setNodes((nodes) => nodes.filter((node) => node.id !== id));
    setEdges((edges) => edges.filter((edge) => edge.source !== id));
  }, [id, setNodes, setEdges]);

  const onClick: MenuProps['onClick'] = (e) => {
    switch (e.key) {
      case 'copy':
        return duplicateNode();
      case 'delete':
        return deleteNode();
    }
  };

  return (
    <div
      className='absolute z-50 rounded-lg __context__'
      style={{ top, left, right, bottom, boxShadow: token.boxShadow }}
      {...rest}
    >
      <Menu
        onClick={onClick}
        items={items}
      />
    </div>
  );
}

export default ContextMenu;
